import { defineStore } from "pinia";
//
import { loginApi, getUserInfoApi } from "@/api/user";
//写法一
const useUserStore = defineStore("user", {
  // options
  state: () => ({
    token: "",
    userInfo: null,
  }),
  //方法：同步异步
  actions: {
    // 发送请求获取到数据
    async getUserToken({ username, password }) {
      try {
        const res = await loginApi({ username, password });
        // console.log(res);
        //存储
        this.token = res.access_token;
        // 本地存储
        this.getUserInfo();
        return Promise.resolve(true);
      } catch (error) {
        // console.log(error);
        return Promise.reject(false);
      }
    },
    //获取用户信息
    async getUserInfo() {
      try {
        const res = await getUserInfoApi();
        // console.log(res);
        //存储
        this.userInfo = res;
        return Promise.resolve(true);
      } catch (error) {
        return Promise.reject(false);
        //console.log(error);
      }
    },
  },
  //计算属性
  getters: {},
  persist: {
    enabled: true,
    strategies: [
      {
        key: "user1",
        storage: localStorage,
      },
    ],
  },
});
//写法二
export default useUserStore;
